<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

/**
 * Class CustomerDocking
 * @property Collection authorities
 * @package App\Models
 * @author luffyzhao@vip.126.com
 */
class CustomerDocking extends Model
{
    protected $fillable = ['callback', 'secret'];
    protected $table = 'customer_docking';

    protected static function boot()
    {
        static::addGlobalScope('orderBy', function (Builder $query){
            $query->orderByDesc('id');
        });
        parent::boot();
    }

    /**
     * 每次修改都会修改secret
     * @param mixed $value
     * @return Model|void
     * @author luffyzhao@vip.126.com
     */
    public function setUpdatedAt($value)
    {
        $this->setAttribute('secret', Str::random());
        parent::setUpdatedAt($value);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * @author luffyzhao@vip.126.com
     */
    public function customer(){
        return $this->belongsTo(Customer::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     * @author luffyzhao@vip.126.com
     */
    public function authorities(){
        return $this->belongsToMany(Callback::class, 'customer_callback_authority', 'customer_id', 'callback_id', 'customer_id', 'id');
    }

    /**
     * @param $value
     * @return string
     * @author luffyzhao@vip.126.com
     */
    protected function getSecretAttribute($value){
        return base64_encode(md5($value . config('app.key')));
    }
}
